import Cocoa

//: # 正则解析
 struct RegexHelper {
  let regex: NSRegularExpression
  
  init(_ pattern: String) throws {
    try regex = NSRegularExpression(pattern: pattern,
                                    options: .caseInsensitive)
  }
  
  func match(_ input:String) -> [NSRange] {
    return regex.matches(in: input, options: [], range: NSMakeRange(0, input.count))
      .map { $0.range }
  }
  
}

/*:
 # 剪切板解析

 - [ ] TODO: 剪贴板内容解析
 
 */

for aType in NSPasteboard.general.types! {
  print(aType)
}


//: # Main
let KMVAR = "KMVAR_VarSource"
let test = """
This method invokes [`processEditing()`](dash-apple-api://load?request_key=hsIxzp7hxm#dash_1525980) if there are no outstanding [`beginEditing()`](dash-apple-api://load?topic_id=1411853&language=swift) calls. `NSTextStorage` invokes this method automatically each time it makes a change to its attributed string. Subclasses that override or add methods that alter their attributed strings directly should invoke this method after making those changes; otherwise you should not invoke this method. The information accumulated with this method is then used in an invocation of [`processEditing()`](dash-apple-api://load?request_key=hsIxzp7hxm#dash_1525980) to report the affected portion of the receiver.

The methods for querying changes, [`editedRange`](dash-apple-api://load?request_key=hsIxzp7hxm#dash_1524379) and [`changeInLength`](dash-apple-api://load?request_key=hsIxzp7hxm#dash_1528400), indicate the extent of characters affected after the change. This method expects the characters before the change because that information is readily available as the argument to whatever method performs the change (such as [`replaceCharacters(in:with:)`](dash-apple-api://load?topic_id=1418451&language=swift)).
"""

let source = test
//let source = ProcessInfo.processInfo.environment[KMVAR] ?? "error"

let ranges = try RegexHelper("\\[.*?\\]\\(dash-apple-api:\\/\\/.*?\\)").match(source)
  .sorted { $0.location > $1.location }

let replaces = ranges.map { (source as NSString).substring(with: $0)
  .split(separator: "]").first!.dropFirst()
  .replacingOccurrences(of: "`", with: "")
  }
  .map { "[`\($0)`](dash://a:\($0))" }
//  .map { print($0) }

var result = source
for (index, range) in ranges.enumerated() {
  result = (result as NSString).replacingCharacters(in: range, with: replaces[index])
}
print(result)


